/**
 * 场景页签管理
 */
function StoryPager() {
	// 页签容器
	this.storyTabCont = $(".tempo-story-tab-cont");
	this.storyTabsCont = $(".tempo-story-cont");
	// 页签容器
	this.storyTabs = $(".tempo-story-tabs");

	this.storyTab = $(".tempo-story-tab");

	// 展开页面按钮
	this.handleBtn = $(".tempo-story-expandBtn");
	// 故事分页左侧切页按钮
	this.storyLeftBtn = $(".tempo-story-cont-leftbtn");
	// 故事分页右侧切页按钮
	this.storyRightBtn = $(".tempo-story-cont-rightbtn");

	this.btnContent = $(".tempo-story-btn-tab");

	//标记为修改的场景
	this._markIds = [];
	
	// 故事id
	this.storyId = null;

	var that = this;

	that.storyTabs.parent().css("overflow", "hidden");

	this.events = {
		// 页签点击事件
		"pagerBeforeClick" : $.noop,
		// 页签点击事件
		"pagerClick" : $.noop,
		//更新描述
		modifyDescription : $.noop
	}
	
	// 左切页事件
	this.storyLeftBtn.on("click", function() {
		this.rollpage.roll('left');
	}.bind(this));
	// 右切页事件
	this.storyRightBtn.on("click", function() {
		this.rollpage.roll('right');
	}.bind(this));

	if (typeof this.render === 'undefined') {
		StoryPager.prototype.render = function(list) {
			var that = this;
			this.storyTabCont.on("click", "span", this.pagerClick.bind(this));
			// 初始化渲染第一个电脑场景
			var isFirst = false, load = false;
			for (var i = 0; i < list.length; i++) {
				if (!isFirst && list[i].device == 'desktop' && list[i].type!='word') {
					isFirst = true;
					load = true;
				}
				if(list[i].type!='report' && list[i].type!='word'){
					this.addPager(list[i], load);
				}
				load = false;
			}
		}

		/**
		 * 页签单击事件
		 */
		StoryPager.prototype.pagerClick = function(e) {
			var span = $(e.target).closest("span"),
				data = span.data("tempoStorypage");
			if(data.type == 'report' || data.type == 'word'){
				$("#tempo-scene-toolbar-snapshot").hide();
			}else{
				$("#tempo-scene-toolbar-snapshot").show();
			}
//			if (this.events.pagerBeforeClick.call(span,data) !== false) {
				this.storyTabCont.find(".tempo-story-tab-curSelect")
						.removeClass("tempo-story-tab-curSelect");
				span.addClass("tempo-story-tab-curSelect");
				this.rollpage.roll("to", span);
				this.events.pagerClick.call(span,data);
//			}

		}

		/**
		 * 为页签注册指定的事件
		 */
		StoryPager.prototype.registEvent = function(key, fn) {
			this.events[key] = fn;
		}
		
		StoryPager.prototype._getNewPage = function(item, selected) {
			var span = $("<span/>", {
				linkId : item.id,
				"data-device" : item.device,
				"data-code" : item.code,
				"data-type" : item.type
			}).data("tempo-storypage", item);
			var label = $("<label/>", {
				title : item.name,
				text : item.name
			}).appendTo(span);
			//如果是报告，则添加报告图标
			if(item.type=='report'){
				return ;
				$("<i/>",{
					"class":"ui-icon tempo-ui-icon tempo-ui-icon-report-mark tempo-story-tab-page-report"
				}).appendTo(span);  
			}
			return span;
		}


		/**
		 * 渲染添加单个页面
		 */
		StoryPager.prototype.addPager = function(item, selected) {
			var span = this._getNewPage(item, selected);
			span.appendTo(this.storyTabCont);
			if (selected === true) {
				span.trigger("click");
			}
			return span;
		}

		/**
		 * 指定位置后面添加单个标签页
		 */
		StoryPager.prototype.addPagerAfter = function(item, target, selected) {
			var span = this._getNewPage(item, selected);
			span.insertAfter(target);
			if (selected === true) {
				span.trigger("click");
			}
			this.pagerDragDrop(span);
			return span;
		}

		/**
		 * 调整页签容器的尺寸
		 */
		StoryPager.prototype.resizePager = function() {
			var width = this.storyTabs.width(),
			padding = this.storyTabsCont.outerWidth(true)- this.storyTabsCont.outerWidth();
			this.storyTabsCont.outerWidth(width - padding);
			this.storyTab.outerWidth(this.storyTabsCont.width()
				- this.btnContent.outerWidth() 
				- this.handleBtn.outerWidth());
			if(this.storyTabCont.find(">span:visible").length>0){
				this.rollpage.resize();
			} 
		}

		/**
		 * 控制页签的是否可显示
		 */
		StoryPager.prototype.visible = function(isShow, callback) {
			var state = isShow === true ? [ 'show', 'hide' ]
					: [ 'hide', 'show' ], pagers = this.storyTabCont
					.find(">span");
			callback = callback || $.noop;
			pagers.each(function() {
				var pager = $(this);
				if (callback(pager) === true) {
					pager[state[0]]();
				} else {
					pager[state[1]]();
				}
			});
			this.resizePager();  
		}

		/**
		 * 通过场景id与设备类型查找设备
		 */
		StoryPager.prototype.find = function(code, device) {
			var selector = ">span";
			if(code){
				selector+="[data-code=\""+code+"\"]";
			}
			if(device){
				selector+="[data-device=\""+device+"\"]";
			}
			var pagers = this.storyTabCont.find(selector);
			var arr = [];
			for (var i = 0; i < pagers.length; i++) {
				var pager = $(pagers[i]), pagerData = pager
						.data("tempoStorypage"); 
				if ((pagerData.device === device || device == null)
						&& (pagerData.code == code || code == null)) {
					arr.push(pager);
				}
			}
			if (arr.length == 1) {
				return arr[0];
			}
			return arr.length == 0 ? null : arr;
		}

		/**
		 * 通过场景id查询页签
		 */
		StoryPager.prototype.findById = function(id) {
			return this.storyTabCont.find(">span[linkId='" + id + "']");
		}

		StoryPager.prototype.loadFirst = function() {
			this.storyTabCont.find(">span:visible:first").trigger("click");
		}
		
		/**
		 * 获取当前页的数据 
		 */
		StoryPager.prototype.getPageData = function(id){
			var page = this.findById(id);
			if(page){
				return page.data("tempoStorypage");
			}
			return null;
		}
		
		/**
		 * 获取当前页的数据 
		 */
		StoryPager.prototype.getPageDataByDeviceCode = function(code, device){
			var page = this.find(code, device); 
			if(page){
				return page.data("tempoStorypage");
			}
			return null; 
		}
		
		/**
		 * 获取所有显示的页的数据
		 */
		StoryPager.prototype.getAllVisibleData = function(){
			var result = [];
			this.storyTabCont.find(">span[linkId]:visible").each(function(i,span){
				result.push($(span).data("tempoStorypage"));
			}); 
			return result;
		}

		/**
		 * 通过场景id加载页面
		 */
		StoryPager.prototype.loadById = function(id) {
			this.findById(id).trigger("click");
		}

		/**
		 * 页签滚动事件
		 */
		StoryPager.prototype.rollpage = (function() {
			// 步长，一次滚动多少像素
			var step = 121,
			// 默认的tabcont的outerWidth
			scrollWidth,
			// 当前marginLeft
			curMarginLeft = 0, btnLeft = this.btnContent.width(), that = this,
			// 获取scrollWidth
			getScrollWidth,
			// 滚动
			roll,
			// 界面大小调整时候，要调整显示样式
			resize,
			// 向左滚动
			rollLeft,
			// 向右滚动
			rollRight,
			// 滚动到指定元素位置
			rollTo,
			// 控制按钮的状态
			ctrlBtnState;

			getScrollWidth = function() {
				return scrollWidth
						|| (scrollWidth = that.storyTabCont.outerWidth(true));
			};
			// 传入方向
			roll = function(direction) {
				getScrollWidth();
				var marginLeft = null;
				if (direction == 'left') {
					marginLeft = rollLeft();
				} else if (direction == 'right') {
					marginLeft = rollRight();
				} else if (direction == 'to') {
					marginLeft = rollTo(arguments[1]);
				}
				if (marginLeft !== null) {
					that.storyTabCont.animate({
						marginLeft : marginLeft
					}, 300);
				}
				resize();
				// ctrlBtnState();
			}
			/**
			 * 点右侧按钮，则margin-left减小 如果最右侧的页签left+width小于等于右侧切换按钮的left,则不能继续
			 */
			rollRight = function() {
				// 获取最右侧页签
				var last = that.storyTabCont.find(">span:visible:last");
				if (last.length == 0){
					return null;
				}
				var left = last
						.position().left
						+ curMarginLeft, width = last.outerWidth(true);
				var storyTabWidth = that.storyTab.outerWidth(true);
				// 获取右侧按钮的left
				// 如果left+width小于等于右侧切换按钮的left 则不能继续，返回0
				if (left + width <= storyTabWidth) {
					return null;
				}
				// 返回新的marginLeft
				return curMarginLeft = curMarginLeft
						- Math.min(left + width - storyTabWidth, step);
			}

			/**
			 * 点左侧按钮，margin-left增大 如果storyTabCont的scrollWidth等于原始的，则不能继续操作
			 */
			rollLeft = function() {
				if (curMarginLeft >= 0) {
					return curMarginLeft = 0;
				}
				return curMarginLeft = curMarginLeft + step > 0 ? 0
						: curMarginLeft + step;
			}

			rollTo = function(item) {
				var itemPos = item.position();
				if (itemPos.left + curMarginLeft <= 0) {
					return curMarginLeft = -itemPos.left;
				}
				var storyTabWidth = that.storyTab.outerWidth(true);
				var left = itemPos.left + item.outerWidth(true);
				if (left + curMarginLeft > storyTabWidth) {
					return curMarginLeft = 0 - left + storyTabWidth;
				}
				return null;
			}

			resize = function() {
				var last = that.storyTabCont.find(">span:visible:last");
				if (curMarginLeft < 0) {
					var lastPos = last.position().left + last.width()
							+ curMarginLeft;
					var left = that.handleBtn.position().left; 
					if (lastPos < left) {
						curMarginLeft = curMarginLeft
								+ (left - lastPos - that.handleBtn
										.outerWidth(true));
						curMarginLeft = curMarginLeft>0?0:curMarginLeft; 
						that.storyTabCont.css("marginLeft", curMarginLeft);
					}
				}
				ctrlBtnState();
			}
			// 控制按钮的状态
			ctrlBtnState = function() {
				var leftOper = curMarginLeft >= 0 ? "addClass" : "removeClass";
				that.storyLeftBtn[leftOper]("tempo-story-cont-btn-disabled");
				// 获取最右侧页签
				var last = that.storyTabCont.find(">span:visible:last"); 
				if (last.length == 0){
					return null;
				}
				var left = last.position().left+ curMarginLeft;
				var width = last.outerWidth(true);
				var storyTabWidth = that.storyTab.outerWidth(true);
				// 如果left+width小于等于右侧切换按钮的left 则不能继续，返回0
				if (left + width <= storyTabWidth) {
					that.storyRightBtn
							.addClass("tempo-story-cont-btn-disabled");
				} else {
					that.storyRightBtn
							.removeClass("tempo-story-cont-btn-disabled");
				}
			}
			return {
				roll : roll,
				resize : resize
			};
		}).call(this);

		/**
		 * 判断当前设备下是否有可见的页
		 */
		StoryPager.prototype.hasVisiblePage = function() {
			return that.storyTabCont.find(">span:visible").length > 0;
		}
	}
}